package com.pmcc.cj.service;

import com.pmcc.cj.entity.*;
import com.pmcc.cj.repository.*;
import com.pmcc.utils.AntdPage;
import com.pmcc.utils.ResultBean;
import com.pmcc.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by tomas on 2020/10/9.
 */
@Transactional
@Service
public class CjCountyProxyService {
    @Autowired
    CjCountyProxyRepository cjCountyProxyRepository;
    @Autowired
    CjAreaAgencyRepository cjAreaAgencyRepository;
    @Autowired
    CjCustomerRepository cjCustomerRepository;
    @Autowired
    CjCountyVillageRepository cjCountyVillageRepository;
    @Autowired
    CjActivationSaleRepository cjActivationSaleRepository;

    public ResultBean queryCountyProxyByPage(CjCountyProxy model, AntdPage antdPage){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Page page=cjCountyProxyRepository.findAll(this.getSpecification(model),antdPage.getPageRequest());
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(page.getContent());
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public Specification<CjCountyProxy> getSpecification(CjCountyProxy model) {
        return new Specification<CjCountyProxy>() {
            @Override
            public Predicate toPredicate(Root<CjCountyProxy> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(StringUtil.isNotEmpty(model.getName())){
                    list.add(builder.like(root.get("name").as(String.class),  "%"+model.getName().trim()+"%"));
                }
                if(model.getFettle() != null){
                    list.add(builder.equal(root.get("fettle").as(Integer.class),  model.getFettle()));
                }
                query.orderBy(builder.desc(root.get("submitTime").as(Date.class)));
                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }
    public ResultBean verificationCountyProxy(String id,String type){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCountyProxy retailer = cjCountyProxyRepository.findOne(id);
            if("1".equals(type)){
                //审核通过
                if(retailer != null){
                    //激活码修改为激活状态
                    //如果是因为用户名没有值的可以认为是还没有县级代理
                    CjAreaAgency areaAgency = cjAreaAgencyRepository.findByActivationCodeAndDelFlag(retailer.getActivationCode(),0);
                    if(areaAgency != null && areaAgency.getBoActive() && areaAgency.getEmployeeId() != null){
                        resultBean.setResultCode(ResultBean.FAIL);
                        resultBean.setResultDesc("不能重复审核");
                        return resultBean;
                    }
                    CjAreaAgency areaAgency1 = cjAreaAgencyRepository.findOne(areaAgency.getParentId());
                    String city = areaAgency1.getAddress();
                    CjAreaAgency areaAgency2 =cjAreaAgencyRepository.findOne(areaAgency1.getParentId());
                    String sheng = areaAgency2.getAddress();
                    //保存县级代理商与县名称到关联表
                    CjCountyVillage cjCountyVillage=cjCountyVillageRepository.findByFettleAndAddress(1,areaAgency.getAddress());
                    if(cjCountyVillage != null){
                        resultBean.setResultCode(ResultBean.FAIL);
                        resultBean.setResultDesc("该县已存在代理商");
                        return resultBean;
                    }else {
                        cjCountyVillage= new CjCountyVillage();
                        cjCountyVillage.setFettle(1);
                        cjCountyVillage.setAddress(areaAgency.getAddress());
                        cjCountyVillage.setCustomerId(retailer.getEmployeeId());
                        cjCountyVillage.setProvince(sheng);
                        cjCountyVillage.setCity(city);
                        cjCountyVillage.setCounty(areaAgency.getAddress());
                        cjCountyVillageRepository.saveAndFlush(cjCountyVillage);
                    }
                    retailer.setFettle(1);
                    retailer.setVerifyTime(new Date());
                    //同时修改为使用状态
                    CjActivationSale cjActivationSale= cjActivationSaleRepository.findByActivationCodeAndDelFlag(retailer.getActivationCode(),0);
                    retailer.setSalesmanId(cjActivationSale.getEmployeeId());
                    retailer.setSalesmanName(cjActivationSale.getEmployeeName());
                    //同时修改为使用状态
                    cjActivationSale.setUseDate(new Date());
                    cjActivationSale.setUseFlag(1);
                    cjActivationSaleRepository.saveAndFlush(cjActivationSale);
                    cjCountyProxyRepository.saveAndFlush(retailer);
                    areaAgency.setBoActive(true);
                    areaAgency.setUseDate(new Date());
                    areaAgency.setEmployeeId(retailer.getEmployeeId());
                    CjCustomer customer = cjCustomerRepository.findOne(retailer.getEmployeeId());
                    customer.setRetailer(2);//把用户设定为代理商
                    customer.setCardName(retailer.getUsername());
                    areaAgency.setEmployee(customer.getCardName());
                    cjAreaAgencyRepository.saveAndFlush(areaAgency);
                    customer.setCounty(areaAgency.getAddress());
                    String parentId = areaAgency.getParentId();
                    //所有的父激活码全部开发
                    for(int i=0;i<2;i++){
                        CjAreaAgency cjAreaAgency = cjAreaAgencyRepository.findOne(parentId);
                        cjAreaAgency.setBoActive(true);
                        cjAreaAgency.setUseDate(new Date());
                        cjAreaAgencyRepository.saveAndFlush(cjAreaAgency);
                        parentId = cjAreaAgency.getParentId();
                        if(i==0){
                            customer.setCity(cjAreaAgency.getAddress());
                        }
                        if(i==1){
                            customer.setProvince(cjAreaAgency.getAddress());
                        }
                    }
                    cjCustomerRepository.saveAndFlush(customer);
                }
            }else {
                //审核拒绝
                if(retailer != null){
                    retailer.setFettle(2);
                    retailer.setVerifyTime(new Date());
                    cjCountyProxyRepository.saveAndFlush(retailer);
                }
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
}
